<?php

/**
 * Created by Atom.
 * User: qiliping
 * Date: 2017/1/15
 * Time: 11:18
 */
class Order_model extends CI_Model
{

  /**
  * 立即购买
  */
  public function buy_now($user_id,$course_id,$num,$type=null)
  {
	$this->db->trans_start();

	if(empty($type)){
		$sql = "SELECT * FROM {$this->db->dbprefix}course where id = '{$course_id}'";
		$course = $this->db->query($sql)->row_array();
		if(empty($course)) return -1;
		$school_id = $course['school_id'];
		if($school_id == 0){
			$school_id = $this->school_id;
		}
	}else{
		if($type == 4){
			$sql = "SELECT * FROM {$this->db->dbprefix}b_subject where id = '{$course_id}'";
			$course = $this->db->query($sql)->row_array();
			if(empty($course)) return -1;
		}
		$school_id = $this->school_id;
	}

	$course_type = !empty($type) ? $type : $course['type'];
	//添加到购物车
	$cart = array(
	  'user_id' => $user_id,
	  'school_id' => $this->school_id,
	  'course_type' => $course_type,
	  'course_id' => $course_id,
	  'quantity' => $num,
	  'cart_type' => 1,
	  'create_on' => time(),
	 );

	 $this->db->insert('shopping_cart',$cart);
	 $cart_id = $this->db->insert_id();


	//添加到结算表
	$settle = array(
	  'user_id' => $user_id,
	  'cart_ids' => $cart_id,
	  'order_type' => $course_type,
	  'school_id' => $school_id,
	  'create_on' => time(),
	 );

	 $this->db->insert('shopping_cart_settle',$settle);
	 $settle_id = $this->db->insert_id();

	$this->db->trans_complete();
	return $settle_id;
  }

  /**
  ** 根据结算id获取购物车信息
  */
  function get_cart_info_by_settle($settle_id, $course_type){
  	if($course_type == 4){
  		$cart_info = $this->get_subject_info($settle_id);
  	}elseif($course_type == 5){
  		$cart_info = $this->get_sx_info($settle_id);
  	}else{
  		$cart_info = $this->get_course_info($settle_id,$course_type);
  	}
	return $cart_info;
  }

  function get_course_info($settle_id,$course_type = 0){
  	if($course_type == 1){
  		$sql = "SELECT cart.*,course.*,s.fx_price FROM {$this->db->dbprefix}shopping_cart cart ".
			" left join {$this->db->dbprefix}course course on course.id = cart.course_id".
			" left join {$this->db->dbprefix}course_shelves s on (course.id = s.course_id and s.school_id = $this->school_id)".
			" WHERE cart.`cart_id` in (SELECT cart_ids FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id})";
  	}else{
  		$sql = "SELECT cart.*,course.* FROM {$this->db->dbprefix}shopping_cart cart ".
			"left join {$this->db->dbprefix}course course on course.id = cart.course_id".
			" WHERE cart.`cart_id` in (SELECT cart_ids FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id})";
  	}


	return $this->db->query($sql)->result_array();
  }

  function get_sx_info($settle_id){
  	$sql = "SELECT cart.*,tp.* FROM {$this->db->dbprefix}shopping_cart cart ".
			"left join {$this->db->dbprefix}o2o_school_sx_packages tp on tp.sx_id = cart.course_id AND tp.school_id = cart.school_id ".
			" WHERE cart.`cart_id` in (SELECT cart_ids FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id}) AND tp.id > 0";

	return $this->db->query($sql)->result_array();
  }

  function get_subject_info($settle_id){
  	$sql = "SELECT cart.*,tp.*,s.title,s.img AS course_img FROM {$this->db->dbprefix}shopping_cart cart ".
			"left join {$this->db->dbprefix}o2o_school_tk_packages tp on tp.subject_id = cart.course_id AND tp.school_id = cart.school_id ".
			"left join {$this->db->dbprefix}b_subject AS s ON(s.id=tp.subject_id) ".
			" WHERE cart.`cart_id` in (SELECT cart_ids FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id}) AND tp.id > 0";

	return $this->db->query($sql)->result_array();
  }

  /**
   * 获取结算信息
   * @param  [type] $settle_id [description]
   * @return [type]            [description]
   */
  public function get_settle_by_id($settle_id)
  {
	$sql = "SELECT * FROM {$this->db->dbprefix}shopping_cart_settle where id = {$settle_id} LIMIT 1";
	return $this->db->query($sql)->row_array();
  }

  /**
  **  获取订单信息
  */
  public function get_order_by_id($order_id)
  {
	$sql = "SELECT * FROM {$this->db->dbprefix}shopping_orders where order_id = {$order_id} LIMIT 1";
	return $this->db->query($sql)->row_array();
  }

  function submit_shixun_order($settle_id, $title = '', $image = ''){
  	$this->db->trans_start();
	$order_id = 0;
	//生成订单编号
	$orderSn = intval(date('Y')) . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

	//查询settle
	$settle_sql = "SELECT * FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id} LIMIT 1";
	$settle = $this->db->query($settle_sql)->row_array();
	if(empty($settle)) return 0;

	//查询用户信息
	$user_sql = "SELECT * FROM {$this->db->dbprefix}user user left join {$this->db->dbprefix}user_account uc on uc.user_id=user.id where id={$settle['user_id']} LIMIT 1";
	$user = $this->db->query($user_sql)->row_array();
	if(empty($user)) return 0;

	//组合course_list
	$course_sql = "SELECT tp.expire_day,school.school_name,tp.price,cart.quantity,cart.course_type,cart.course_id FROM {$this->db->dbprefix}shopping_cart cart ".
			" left join {$this->db->dbprefix}o2o_school school on school.id = '{$settle['school_id']}' ".
			" left join {$this->db->dbprefix}o2o_school_sx_packages tp on tp.sx_id = cart.course_id AND tp.school_id = cart.school_id ".
			" WHERE cart.`cart_id` in ({$settle['cart_ids']})";

	$course_list = $this->db->query($course_sql)->result_array();
	$total_product_amount = 0.0;//课程总价
	$total_order_amount = 0.0;//订单总价
	$payment_money_amount = 0.0;//支付总价
// print_r($course_list);exit;
	//计算总价
	foreach ($course_list as $key => $course) {
		$course_list[$key]['id'] = $course['course_id'];
		$course_list[$key]['title'] = $title;
		$course_list[$key]['course_img'] = $image;
	  	$total_product_amount += $course['price'] * $course['quantity'];
	}
	$total_order_amount = $total_product_amount;
	$payment_money_amount = $total_order_amount;

	//添加订单
	$order_data = array(
	  'order_num' => $orderSn,
	  'buyer_user_id' => $user['id'],
	  'buyer_user_name' => $user['nick'],
	  'buyer_user_phone' => $user['mobile'],
	  'school_id' => $this->school_id,
	  'order_type' => $settle['order_type'],
	  'order_products' => json_encode($course_list),
	  'discount_summary' => '',
	  'total_product_amount' => $total_product_amount,
	  'total_freight_amount' => 0,
	  'total_discount_amount' => 0,
	  'total_order_amount' => $total_order_amount,
	  'payment_integral' => 0,
	  'payment_integral_amount' => 0,
	  'payment_money_amount' => $payment_money_amount,
	  'payment_method' => 0,
	  'payment_status' => 0,
	  'order_comment' => '',
	  'province_code' => $user['province_code'],
	  'province_name' => $user['province_name'],
	  'city_code' => $user['city_code'],
	  'city_name' => $user['city_name'],
	  'district_code' => $user['district_code'],
	  'district_name' => $user['district_name'],
	  'street_code' => $user['street_code'],
	  'street_name' => $user['street_name'],
	  'order_time' => time(),
	  'order_status' => 0,
	);
	$this->db->insert('shopping_orders',$order_data);
	$order_id = $this->db->insert_id();

// print_r($course_list);
	//添加订单明细
	foreach ($course_list as $course) {
	  $item = array(
		  'order_id' => $order_id,
		  'course_id' => $course['course_id'],
		  'school_id' => $settle['school_id'],
		  'course_type' => $course['course_type'],
		  'course_name' => $title,
		  'course_img' => $image,
		  'effective_time' => $course['expire_day'],
		  'course_price' => $course['price'],
		  'quantity' => $course['quantity'],
		  'item_status' => 0,
		  'create_on' => time(),
		);
		$this->db->insert('shopping_order_item',$item);

	}

	//添加订单记录
	$history = array(
	  'order_id' => $order_id,
	  'comment' => '用户提交订单',
	  'order_status' => 0,
	  'create_on' => time(),
	  'create_by' => 'user',
	);
	$this->db->insert('shopping_order_history',$history);

	//删除购物车信息
	$this->db->query("delete FROM {$this->db->dbprefix}shopping_cart WHERE cart_id IN ({$settle['cart_ids']})");
	//删除结算信息
	$this->db->query("delete FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id}");

	$this->db->trans_complete();

	return $order_id;
  }

  function submit_subject_order($settle_id){
  	$this->db->trans_start();
	$order_id = 0;
	//生成订单编号
	$orderSn = intval(date('Y')) . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

	//查询settle
	$settle_sql = "SELECT * FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id} LIMIT 1";
	$settle = $this->db->query($settle_sql)->row_array();
	if(empty($settle)) return 0;

	//查询用户信息
	$user_sql = "SELECT * FROM {$this->db->dbprefix}user user left join {$this->db->dbprefix}user_account uc on uc.user_id=user.id where id={$settle['user_id']} LIMIT 1";
	$user = $this->db->query($user_sql)->row_array();
	if(empty($user)) return 0;

	//组合course_list
	$course_sql = "SELECT s.id,s.school_id,tp.expire_day,school.school_name,s.title,s.img,tp.price,cart.quantity,cart.course_type FROM {$this->db->dbprefix}shopping_cart cart ".
			" left join {$this->db->dbprefix}b_subject s on s.id = cart.course_id ".
			" left join {$this->db->dbprefix}o2o_school school on school.id = s.school_id ".
			" left join {$this->db->dbprefix}o2o_school_tk_packages tp on tp.subject_id = cart.course_id AND tp.school_id = cart.school_id ".
			" WHERE cart.`cart_id` in ({$settle['cart_ids']})";

	$course_list = $this->db->query($course_sql)->result_array();
	$total_product_amount = 0.0;//课程总价
	$total_order_amount = 0.0;//订单总价
	$payment_money_amount = 0.0;//支付总价

	//计算总价
	foreach ($course_list as $course) {
	  $total_product_amount += $course['price'] * $course['quantity'];
	}
	$total_order_amount = $total_product_amount;
	$payment_money_amount = $total_order_amount;

	//添加订单
	$order_data = array(
	  'order_num' => $orderSn,
	  'buyer_user_id' => $user['id'],
	  'buyer_user_name' => $user['nick'],
	  'buyer_user_phone' => $user['mobile'],
	  'school_id' => $this->school_id,
	  'order_type' => $settle['order_type'],
	  'order_products' => json_encode($course_list),
	  'discount_summary' => '',
	  'total_product_amount' => $total_product_amount,
	  'total_freight_amount' => 0,
	  'total_discount_amount' => 0,
	  'total_order_amount' => $total_order_amount,
	  'payment_integral' => 0,
	  'payment_integral_amount' => 0,
	  'payment_money_amount' => $payment_money_amount,
	  'payment_method' => 0,
	  'payment_status' => 0,
	  'order_comment' => '',
	  'province_code' => $user['province_code'],
	  'province_name' => $user['province_name'],
	  'city_code' => $user['city_code'],
	  'city_name' => $user['city_name'],
	  'district_code' => $user['district_code'],
	  'district_name' => $user['district_name'],
	  'street_code' => $user['street_code'],
	  'street_name' => $user['street_name'],
	  'order_time' => time(),
	  'order_status' => 0,
	);
	$this->db->insert('shopping_orders',$order_data);
	$order_id = $this->db->insert_id();


	//添加订单明细
	foreach ($course_list as $course) {
	  if($course['type']!=3){
		//非班课
		$item = array(
		  'order_id' => $order_id,
		  'course_id' => $course['id'],
		  'school_id' => $course['school_id'],
		  'course_type' => $course['course_type'],
		  'course_name' => $course['title'],
		  'course_img' => $course['img'],
		  'effective_time' => $course['expire_day'],
		  'course_price' => $course['price'],
		  'quantity' => $course['quantity'],
		  'item_status' => 0,
		  'create_on' => time(),
		);
		$this->db->insert('shopping_order_item',$item);
	  }

	}

	//添加订单记录
	$history = array(
	  'order_id' => $order_id,
	  'comment' => '用户提交订单',
	  'order_status' => 0,
	  'create_on' => time(),
	  'create_by' => 'user',
	);
	$this->db->insert('shopping_order_history',$history);

	//删除购物车信息
	$this->db->query("delete FROM {$this->db->dbprefix}shopping_cart WHERE cart_id IN ({$settle['cart_ids']})");
	//删除结算信息
	$this->db->query("delete FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id}");

	$this->db->trans_complete();

	return $order_id;
  }

  /**
  **  提交订单
  */
  public function submit_order($settle_id,$course_type = 0)
  {
	$this->db->trans_start();
	$order_id = 0;
	//生成订单编号
	$orderSn = intval(date('Y')) . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

	//查询settle
	$settle_sql = "SELECT * FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id} LIMIT 1";
	$settle = $this->db->query($settle_sql)->row_array();
	if(empty($settle)) return 0;

	//查询用户信息
	$user_sql = "SELECT * FROM {$this->db->dbprefix}user user left join {$this->db->dbprefix}user_account uc on uc.user_id=user.id where id={$settle['user_id']} LIMIT 1";
	$user = $this->db->query($user_sql)->row_array();
	if(empty($user)) return 0;

	//组合course_list
	if($course_type == 1){
		$course_sql = "SELECT course.id,s.expire_day,course.effective_time,course.price,course.school_id,school.school_name,course.title,course.type,course.course_img,s.fx_price,s.commission,cart.quantity FROM {$this->db->dbprefix}shopping_cart cart ".
			" left join {$this->db->dbprefix}course course on course.id = cart.course_id ".
			" left join {$this->db->dbprefix}o2o_school school on school.id = course.school_id ".
			" left join {$this->db->dbprefix}course_shelves s on (cart.school_id = s.school_id AND s.course_id = cart.course_id) ".
			" WHERE cart.`cart_id` in ({$settle['cart_ids']})";
			// echo $course_sql;exit;
	}else{
		$course_sql = "SELECT course.id,course.effective_time,course.school_id,school.school_name,course.title,course.type,course.course_img,course.price,cart.quantity FROM {$this->db->dbprefix}shopping_cart cart ".
			" left join {$this->db->dbprefix}course course on course.id = cart.course_id ".
			" left join {$this->db->dbprefix}o2o_school school on school.id = course.school_id ".
			" WHERE cart.`cart_id` in ({$settle['cart_ids']})";
	}


	$course_list = $this->db->query($course_sql)->result_array();
	// print_r($course_list);exit;

	$total_product_amount = 0.0;//课程总价
	$total_order_amount = 0.0;//订单总价
	$payment_money_amount = 0.0;//支付总价
	$total_order_commission = 0.0;//订单佣金

	//计算总价
	foreach ($course_list as $k => $course) {
		if($course['school_id'] == 0){
			$course_list[$k]['price'] = $price = $course['fx_price'];
		}else{
			$price = $course['price'];
		}
	  	$total_product_amount += $price * $course['quantity'];
	  	if($course_type == 1 ){
	  		$total_order_commission += ($price * $course['quantity']) * $course['commission'] / 100;//计算佣金价格
	  	}
	}
	$total_order_amount = $total_product_amount;
	$payment_money_amount = $total_order_amount;

	//添加订单
	$order_data = array(
	  'order_num' => $orderSn,
	  'buyer_user_id' => $user['id'],
	  'buyer_user_name' => $user['nick'],
	  'buyer_user_phone' => $user['mobile'],
	  'school_id' => $this->school_id,
	  'order_type' => $settle['order_type'],
	  'order_products' => json_encode($course_list),
	  'discount_summary' => '',
	  'total_product_amount' => $total_product_amount,
	  'total_freight_amount' => 0,
	  'total_discount_amount' => 0,
	  'total_order_amount' => $total_order_amount,
	  'total_order_commission' => $total_order_commission,
	  'payment_integral' => 0,
	  'payment_integral_amount' => 0,
	  'payment_money_amount' => $payment_money_amount,
	  'payment_method' => 0,
	  'payment_status' => 0,
	  'order_comment' => '',
	  'province_code' => $user['province_code'],
	  'province_name' => $user['province_name'],
	  'city_code' => $user['city_code'],
	  'city_name' => $user['city_name'],
	  'district_code' => $user['district_code'],
	  'district_name' => $user['district_name'],
	  'street_code' => $user['street_code'],
	  'street_name' => $user['street_name'],
	  'order_time' => time(),
	  'order_status' => 0,
	);
	$this->db->insert('shopping_orders',$order_data);
	$order_id = $this->db->insert_id();


	//添加订单明细
	foreach ($course_list as $course) {
	  if($course['type']!=3){
		//非班课
		$item = array(
		  'order_id' => $order_id,
		  'course_id' => $course['id'],
		  'school_id' => $course['school_id'],
		  'course_type' => $course['type'],
		  'course_name' => $course['title'],
		  'course_img' => $course['course_img'],
		  'effective_time' => $course['effective_time'],
		  'course_price' => $course['price'],
		  'quantity' => $course['quantity'],
		  'commission' => $course['commission'],
		  'item_status' => 0,
		  'create_on' => time(),
		);
		if($course['school_id'] == 0){
			$item['course_price'] = $course['fx_price'];
			$item['effective_time'] = $course['expire_day'];
		}
		$this->db->insert('shopping_order_item',$item);
	  }

	}

	//添加订单记录
	$history = array(
	  'order_id' => $order_id,
	  'comment' => '用户提交订单',
	  'order_status' => 0,
	  'create_on' => time(),
	  'create_by' => 'user',
	);
	$this->db->insert('shopping_order_history',$history);

	//删除购物车信息
	$this->db->query("delete FROM {$this->db->dbprefix}shopping_cart WHERE cart_id IN ({$settle['cart_ids']})");
	//删除结算信息
	$this->db->query("delete FROM {$this->db->dbprefix}shopping_cart_settle WHERE id ={$settle_id}");

	//1111取用户层级
	$parent_sql = "SELECT parent1,parent2,parent3 FROM {$this->db->dbprefix}user WHERE id = {$settle['user_id']}";
	$parent_user = $this->db->query($parent_sql)->row_array();

	//2222取佣金分配规则
	$fx_setting_sql = "SELECT * FROM {$this->db->dbprefix}m_fenxiao_setting WHERE school_id = {$settle['school_id']}";
	$fx_setting = $this->db->query($fx_setting_sql)->row_array();

	if($fx_setting){
		// print_r($total_order_commission * $fx_setting['one_ratio'] / 100);exit;
		if(!empty($parent_user['parent1']) && $parent_user['parent1'] > 0){

			//添加上级佣金  edu_user_commission
			$user_commission = array(
				'user_id' => $parent_user['parent1'],
				'commission' => $total_order_commission * $fx_setting['one_ratio'] / 100,
				'order_id' => $order_id,
				'status' => 0,
				'level' => 1,
				'order_num' => $orderSn,
				'arrive_time' => 0,
				'add_time' => time(),
				);
			$this->db->insert('user_commission',$user_commission);
		}

		if(!empty($parent_user['parent2']) && $parent_user['parent2'] > 0){

			//添加上级佣金  edu_user_commission
			$user_commission = array(
				'user_id' => $parent_user['parent2'],
				'commission' => $total_order_commission * $fx_setting['two_ratio'] / 100,
				'order_id' => $order_id,
				'status' => 0,
				'level' => 2,
				'order_num' => $orderSn,
				'arrive_time' => 0,
				'add_time' => time(),
				);
			$this->db->insert('user_commission',$user_commission);
		}

		if(!empty($parent_user['parent3']) && $parent_user['parent3'] > 0){

			//添加上级佣金  edu_user_commission
			$user_commission = array(
				'user_id' => $parent_user['parent3'],
				'commission' => $total_order_commission * $fx_setting['three_ratio'] / 100,
				'order_id' => $order_id,
				'status' => 0,
				'level' => 3,
				'order_num' => $orderSn,
				'arrive_time' => 0,
				'add_time' => time(),
				);
			$this->db->insert('user_commission',$user_commission);
		}

	}



	$this->db->trans_complete();

	return $order_id;
  }

  /**
   * 面授课报名
   * @param  [type] $settle_id [description]
   * @return [type]            [description]
   */
  public function banke_signup($user_id,$course_id,$data)
  {

	$this->db->trans_start();
	$order_id = 0;
	//生成订单编号
	$orderSn = intval(date('Y')) . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));


	//1.查询用户信息
	$user_sql = "SELECT * FROM {$this->db->dbprefix}user user left join {$this->db->dbprefix}user_account uc on uc.user_id=user.id where id={$user_id} LIMIT 1";
	$user = $this->db->query($user_sql)->row_array();
	if(empty($user)) return 0;

	//2.组合course
	$course_sql = "SELECT * FROM {$this->db->dbprefix}course where id={$course_id} limit 1";
	$course_info = $this->db->query($course_sql)->row_array();
	if(empty($course_info)) return 404;//课程不存在

	$total_product_amount = $course_info['price'];//课程总价
	$total_order_amount = $course_info['price'];//订单总价
	$payment_money_amount = 0.0;//支付总价


	$student_id = 0;//学员信息
	//3.判断学生信息是否存在
	$sql = "SELECT * FROM {$this->db->dbprefix}o2o_student where user_id = {$user_id} limit 1";
	$student_info = $this->db->query($sql)->row_array();

	if(empty($student_info)){
	  //不存在，添加
	  $student = array(
		'user_id' => $user_id,
		'name' => $data['name'],
		'phone' => $data['phone'],
		'birthday' => $data['birthday'],
		'sex' => $data['sex'],
		'wx' => $data['wx'],
		'qq' => $data['qq'],
		'edu' => $data['edu'],
		'on_job' => $data['on_job'],
		'workstation' => '',
		'class_time' => json_encode( $data['class_time']),
		'address' => $data['address'],
		'remark' => $data['remark'],
		'add_time' => time()
	  );

	  $this->db->insert('o2o_student', $student);
	  $student_id = $this->db->insert_id();
	}else{
	  $student_id = $student_info['student_id'];

	  //存在，update
	  $student = array(
		'name' => $data['name'],
		'phone' => $data['phone'],
		'sex' => $data['sex'],
		'wx' => empty($data['wx'])?'':$data['wx'],
		'qq' => empty($data['qq'])?'':$data['qq'],
		'edu' => $data['edu'],
		'class_time' => isset($data['class_time']) ? json_encode( $data['class_time']):"",
		'remark' => $data['remark'],
	  );

	  $this->db->update('o2o_student', $student,array('student_id' => $student_info['student_id']));
	}

	//4.添加school_student
	$school_student_count = $this->db->query("SELECT COUNT(0) count from {$this->db->dbprefix}o2o_school_student where school_id={$course_info['school_id']} and student_id={$student_id} ")->row_array();
	if($school_student_count['count']==0){
	  //不存在，insert
	  $school_student = array(
	  'school_id' => $course_info['school_id'],
	  'school_campus_id' => $data['campus'],
	  'user_id' => $user_id,
	  'student_id' => $student_id,
	  'from' => 0,
	  'name' => $data['name'],
	  'mobile' => $data['phone'],
	  'address' => $data['address'],
	  'sort' => 0,
	  'status' => 1,
	  'add_time' => time(),
	  );
	  $this->db->insert('o2o_school_student', $school_student);
	}


	$order_products = array(
	  'course_img' => $course_info['course_img'],
	  'title' => $course_info['title'],
	  'course_id' => $course_id,
	  'school_name' => '',
	  'price' => $course_info['price'],
	  'quantity' => 1
	  );




	//5.添加订单
	$order_data = array(
	  'order_num' => $orderSn,
	  'buyer_user_id' => $user_id,
	  'buyer_user_name' => $data['name'],
	  'buyer_user_phone' => $data['phone'],
	  'school_id' => $this->school_id,
	  'school_campus_id' => $data['campus'],
	  'order_type' => $course_info['type'],
	  'order_products' => json_encode(Array($order_products)),
	  'discount_summary' => '',
	  'total_product_amount' => $total_product_amount,
	  'total_freight_amount' => 0,
	  'total_discount_amount' => 0,
	  'total_order_amount' => $total_order_amount,
	  'payment_integral' => 0,
	  'payment_integral_amount' => 0,
	  'payment_money_amount' => $payment_money_amount,
	  'payment_method' => 0,
	  'payment_status' => 0,
	  'order_comment' => '',
	  'province_code' => $user['province_code'],
	  'province_name' => $user['province_name'],
	  'city_code' => $user['city_code'],
	  'city_name' => $user['city_name'],
	  'district_code' => $user['district_code'],
	  'district_name' => $user['district_name'],
	  'street_code' => $user['street_code'],
	  'street_name' => $user['street_name'],
	  'address' => $data['address'],
	  'order_comment' => $data['remark'],
	  'order_time' => time(),
	  'order_status' => 0,
	);
	$this->db->insert('shopping_orders',$order_data);
	$order_id = $this->db->insert_id();

	if($course_info['type']==3){
	  //6.班课，查询该课程关联的线下课]course_subject
	  $offline_course_sql = "SELECT oc.id,oc.school_id,oc.title,oc.course_img,oc.price FROM {$this->db->dbprefix}course_subject sub left join {$this->db->dbprefix}o2o_course oc on oc.id = sub.subject_id where sub.course_id = {$course_id}";

	  $offline_course_list = $this->db->query($offline_course_sql)->result_array();
	  foreach ($offline_course_list as $oco) {
	  	//插入订单item
		$item = array(
		  'order_id' => $order_id,
		  'course_id' => $oco['id'],
		  'school_id' => $oco['school_id'],
		  'course_type' => $course_info['type'],
		  'course_name' => $oco['title'],
		  'course_img' => $oco['course_img'],
		  'course_price' => $oco['course_img'],
		  'quantity' => $course_info['price'],
		  'item_status' => 0,
		  'create_on' => time(),
		);
		$this->db->insert('shopping_order_item',$item);

		//插入student_course
		// $stu_cour = array(
		// 	'user_id' => $user_id,
		// 	'student_id' => $student_id,
		// 	'course_id' => $oco['id'],
		// 	'course_type' => 3,
		// 	'school_id' => $oco['school_id'],
		// 	'effective_time' => 0,
		// 	'order_num' => $orderSn,
		// 	'status' => 0,
		// 	'add_time' => time(),
    // );
	  // 	$this->db->insert("o2o_student_course",$stu_cour);
	  }
	}

	//7.添加订单记录
	$history = array(
	  'order_id' => $order_id,
	  'comment' => '用户提交订单',
	  'order_status' => 0,
	  'create_on' => time(),
	  'create_by' => 'user',
	);
	$this->db->insert('shopping_order_history',$history);

	$this->db->trans_complete();

	return $order_id;
  }



  /**
   * 订单支付成功的处理
   * @param  [type] $order_id [description]
   * @return [type]           [description]
   */
  public function order_pay_success($order_id)
  {
	$this->db->trans_start();
	//查询订单信息
	$sql = "SELECT * FROM {$this->db->dbprefix}shopping_orders where order_id = {$order_id} LIMIT 1";
	$order = $this->db->query($sql)->row_array();
	if(empty($order)) return -1;//订单不存在
	if($order['payment_status']==2) return -2;//已经支付过了

	//1、更新order状态
	$order_new = array(
	  'payment_status' => 2,
	  'payment_time' => time(),
	  'order_status' => 1,
	);
	$this->db->update('shopping_orders',$order_new, array('order_id' => $order_id ));

	//2、往学校学员表插入学员数据
	//2.1查询学生表信息o2o_student
	$student_sql = "SELECT * FROM {$this->db->dbprefix}o2o_student WHERE user_id = {$order['buyer_user_id']} LIMIT 1";
	$student = $this->db->query($student_sql)->row_array();

	//2.2查询学员是否存在
	if($order['order_type'] == 3){
	  $stu = $this->db->query("SELECT * FROM {$this->db->dbprefix}o2o_school_student where user_id = {$order['buyer_user_id']} AND school_id={$order['school_id']} LIMIT 1")->row_array();
	  if(empty($stu)){
		//不存在，添加
		$student = array(
		  	'school_id' => $order['school_id'],
		  	'user_id' => $order['buyer_user_id'],
		  	'student_id' => $student['student_id'],
		  	'name' =>  $order['buyer_user_name'],
		  	'mobile' =>  $order['buyer_user_phone'],
		  	'address' =>  $order['address'],
		  	'sort' =>  0,
		  	'status' =>  1,
		  	'add_time' =>  time(),
		);
		$this->db->insert("o2o_school_student",$student);
	  }
	}


	//3、记录学员课程edu_o2o_student_course
	$order_item_sql = "SELECT * FROM {$this->db->dbprefix}shopping_order_item WHERE order_id={$order_id}";
	$order_items = $this->db->query($order_item_sql)->result_array();

	foreach ($order_items as $oitem) {
		$nouse_code_count = $this->get_course_code_count($this->school_id,$oitem['course_id']);
		if($nouse_code_count > 0){
			$data_codes['use_uid'] = $student['user_id'];
			$this->db->where(array('school_id'=>$this->school_id,'course_id'=>$oitem['course_id']));
			$this->db->update('o2o_school_system_video_course_codes',$data_codes);
		}else{
			$stu_cour['code_status'] = 0;
		}
	  	$stu_cour = array(
			'user_id' => $student['user_id'],
			'student_id' => $student['student_id'],
			'course_id' => $oitem['course_id'],
			'course_type' => $oitem['course_type'],
			'school_id' => $oitem['school_id'],
			'effective_time' => $oitem['effective_time'],
			'order_num' => $order['order_num'],
			'status' => 0,
			'add_time' => time(),
	 	 );
	  	$this->db->insert("o2o_student_course",$stu_cour);
	}

	//4、添加订单记录
	$history = array(
	  	'order_id' => $order_id,
	  	'comment' => '用户支付',
	  	'order_status' => 0,
	  	'create_on' => time(),
	  	'create_by' => 'user',
	);
	$this->db->insert('shopping_order_history',$history);

	$this->db->trans_complete();
  }
  	function get_course_code_count($school_id = 0,$course_id = 0){
  		$sql = "SELECT count(id) as count from {$this->db->dbprefix}o2o_school_system_video_course_codes where use_uid = 0 and school_id = $school_id and course_id='{$course_id}'";
  		$result = $this->db->query($sql)->row_array();
        return $result['count'];
  	}

  	function get_tk_subject_order($subject_id, $uid, $school_id, $expire_day = 0){
  		$where = "item.course_id = '{$subject_id}' AND o.school_id='{$school_id}' AND o.order_type = 4 AND o.order_status = 2 AND o.buyer_user_id='{$uid}'";
  		if($expire_day > 0){
  			$time = time();
  			$expire_time = 24 * 3600 * $expire_day;
  			$where .= " AND $time <= (o.payment_time + $expire_time)";
  		}
  		$sql = "SELECT * FROM {$this->db->dbprefix}shopping_orders AS o ";
  		$sql .= "LEFT JOIN {$this->db->dbprefix}shopping_order_item AS item ON(item.order_id=o.order_id) ";
  		$sql .= "WHERE $where";
  		$order_info = $this->db->query($sql)->row_array();
  		return $order_info;
  	}

  	function get_sx_order($sx_id, $uid, $school_id, $expire_day = 0){
  		$where = "item.course_id = '{$sx_id}' AND o.school_id='{$school_id}' AND o.order_type = 5 AND o.order_status = 2 AND o.buyer_user_id='{$uid}'";
  		if($expire_day > 0){
  			$time = time();
  			$expire_time = 24 * 3600 * $expire_day;
  			$where .= " AND $time <= (o.payment_time + $expire_time)";
  		}
  		$sql = "SELECT * FROM {$this->db->dbprefix}shopping_orders AS o ";
  		$sql .= "LEFT JOIN {$this->db->dbprefix}shopping_order_item AS item ON(item.order_id=o.order_id) ";
  		$sql .= "WHERE $where";
  		$order_info = $this->db->query($sql)->row_array();
  		return $order_info;
  	}

  	/**
  	 * 获取分销订单
  	 * @param  [type]  $user_id [description]
  	 * @param  integer $limit   [description]
  	 * @param  integer $offset  [description]
  	 * @return [type]           [description]
  	 */
  	function get_fx_order_list_by_user($user_id,$limit = 0 ,$offset = 10){
  		$this->db->trans_start();

		$sql = "SELECT SQL_CALC_FOUND_ROWS * from {$this->db->dbprefix}user_commission
		  where user_id = {$user_id} LIMIT $limit, $offset;";

		$result = $this->db->query($sql)->result_array();
		$row_num =  $this->db->query('SELECT FOUND_ROWS() as row_num;')->row_array();
		$this->db->trans_complete();

		return array("total_count" => $row_num['row_num'], "result" => $result);

  	}

}
